package com.shop.controller;

import com.shop.dao.ProductDao;
import com.shop.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    @Autowired
    private ProductDao productDao;

    // 获取所有商品
    @GetMapping
    public List<Product> getAllProducts() {
        return productDao.getAllProducts();
    }

    // 根据ID获取商品
    @GetMapping("/{id}")
    public ResponseEntity<Product> getProduct(@PathVariable int id) {
        Product product = productDao.getProductById(id);
        return product != null ? ResponseEntity.ok(product) : ResponseEntity.notFound().build();
    }

    // 根据商家ID获取商品
    @GetMapping("/merchant/{merchant_id}")
    public ResponseEntity<List<Product>> getProductsByMerchant_id(@PathVariable int merchant_id) {
        // 调用ProductDao的方法根据商家ID获取商品列表
        List<Product> products = productDao.getProductByMerchant_id(merchant_id);

        // 如果有商品则返回 200 和商品列表，如果没有商品则返回 204 No Content
        return (products != null && !products.isEmpty())
                ? ResponseEntity.ok(products)
                : ResponseEntity.noContent().build();
    }

    // 创建商品
    @PostMapping
    public ResponseEntity<Product> addProduct(@RequestBody Product product) {
        productDao.insertProduct(product);
        return new ResponseEntity<>(product, HttpStatus.CREATED);
    }

    // 更新商品
    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(@PathVariable int id, @RequestBody Product productDetails) {
        productDetails.setId(id);
        productDao.updateProduct(productDetails);
        return ResponseEntity.ok(productDetails);
    }


    // 删除商品
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable int id) {
        productDao.deleteProduct(id);
        return ResponseEntity.noContent().build();
    }
}
